package com.zhiwang.planet.mvvm.viewmodel.zygote

import androidx.lifecycle.switchMap
import androidx.paging.toLiveData
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.viewmodel.withdraw.Listing
import com.zhiwang.planet.util.ReflectUtil
import java.lang.reflect.ParameterizedType

abstract class SimplePageKeyedRepository<FACTORY, KEY, VALUE> constructor(val restApi: RestApi) {


    fun listingSource(): Listing<VALUE> {
        val factory = createFactory() as SimplePageKeyedDataSourceFactory<Int, VALUE>

        val pagedList = factory.toLiveData(
                pageSize = 12,
                initialLoadKey = 0
        )


        val loadingMoreState = factory.sourceLiveData.switchMap { it.loadingState }

        val refreshingState = factory.sourceLiveData.switchMap { it.refreshingState }

        val err = factory.sourceLiveData.switchMap { it.errState }

        val initLoadDone  = factory.sourceLiveData.switchMap { it.initLoadDone }

        return Listing(
                pagedList = pagedList,
                refreshing = refreshingState,
                loadingMoreState = loadingMoreState,
                err = err,
                initLoadDone = initLoadDone
        )
    }

    private fun createFactory(): FACTORY {

        val factoryType = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]

        val factoryClass = ReflectUtil.getRawType(factoryType)

        return factoryClass.constructors[0].newInstance(restApi) as FACTORY
    }
}